package com.qf.game.servlet;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.qf.framwork.annotation.ResponseBody;
import com.qf.framwork.base.BaseServlet;
import com.qf.game.entity.Orders;
import com.qf.game.service.OrdersService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 支付宝的servlet
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
@WebServlet("/alipayServlet")
public class AliPayServlet extends BaseServlet {

    private static AlipayClient alipayClient;

    private OrdersService ordersService = new OrdersService();

    static {
        //AlipayClient - 支付宝的核心对象（支付/查询/退款...） 应该是全局唯一
        alipayClient =  new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do", //沙箱支付网关
                "2016073000127352",
                "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDIrP/cTBmNsHD2TxxoIV1jPFAYZemeaz1HdGgVm1HiQPJTiiz7uH/wbmrHNwCipcgypHFrGAD2ARTzzQe3CumH7KEve0VqsFQwhuLehAQV8XTX41nBCBQuVghHRCy1NvW+2FYlcf4yE6czW0SJtdk5HH0G17ms2nQAHN0ytAK1dkGPjEUyiJnKP6IA69GLyu9AldRfAOS9wE0SzC++w9m1wIZo357ciMz71NG8dMSE471SRytSRNgrAr9REkduDLcEmgFBgS+F0EM/+Pz2ty8qwF48EDBhjqYSBNsDmay4xS6qw1AvZphPn72lneGBmBXosalNvlu8PMezgIGHER35AgMBAAECggEAVadp6ljdC1pFTQzFXjjniITk1xUg20qAtHAeQSKzl7QK+tdeje7ZRQGMOA3lCodiZSNFeeWb+2TI0asw4NMajLbWsdKW9Yvf03qveTS2HbubGM7kr3zISGLWU7zorEySJexnE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//商户私钥
                "json", //数据格式 - json
                "utf-8", //编码
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx+n+pEqTVi27mtj3CuUQXi2ixqeeTwE/0tGrW+sg6xtfajvJV67GYf2zzNxxBV0TYfhdbi70VI3DftEijg7GSNKoOilAu2DKQFqidnSxmN1Es1oRTaiaehqm1Uzs2uswpzBVR21iygLHujwthC8kNkMgxVFkjbE/qTn7z5wlsailtg6wF+hY3BcDCiaLyVLjEDngmrLyLXPLenjAuvXq20h9zV7CW9HXuhpPBDfsn4fv5TjgEl1smjJNr4O/VxICKDNPsvrCyNXhfroK9PEFFwH+4IWGeBUJAP2cSufNU0OA+UH+2xQnaR8Cz30QIgIslckBGuXQZvxqaY2mMMz14QIDAQAB",
                "RSA2");  //获得初始化的AlipayClient
    }

    /**
     * 调用支付宝支付
     */
    @ResponseBody
    public void pay(Integer oid, HttpServletResponse response) throws IOException {
        //通过oid查询需要支付的订单
        System.out.println("调用支付宝支付！" + oid);
        Orders orders = ordersService.getOrdersById(oid);
        System.out.println("需要支付的获得的订单：" + orders);

        //调用支付宝的SDK进行支付的请求
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); //创建API对应的request
        alipayRequest.setReturnUrl( "http://localhost:8080/index.jsp" ); //同步通知，当支付完成后跳转到哪个页面
        alipayRequest.setNotifyUrl( "http://verygoodwlk.xicp.net/alipayServlet?method=payResult" ); //异步通知，支付完成后，支付宝服务器会主动的给这个地址发送一个请求，这个请求里面携带了支付结果
        //组装支付请求的json
        alipayRequest.setBizContent( "{"  +
                "    \"out_trade_no\":\"" + orders.getOrderId() + "\","  +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\","  +
                "    \"total_amount\":" + orders.getMoney() + ","  +
                "    \"subject\":\"欢乐豆" + orders.getHappeyBean() + "个\""  +
                "  }" ); //填充业务参数
        String form= "" ;
        try  {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单 返回的就是一个Html页面
        }  catch  (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType( "text/html;charset=utf-8");
        response.getWriter().write(form); //直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    /**
     * 支付的回调结果 xxxx?method=payResult&支付宝的参数
     */
    @ResponseBody
    public String payResult(HttpServletRequest request, HttpSession session) throws AlipayApiException {
        System.out.println("=============》接收到支付宝发送过来的支付返回结果！！！！！！");

        //转换 -> Map<String, String[]> -> Map<String, String>
//        Map<String, String[]> parameterMap = request.getParameterMap();
//        Map<String, String> paramsMap = new HashMap<>();
//        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
////            System.out.println(entry.getKey() + "  " + entry.getValue()[0]);
//            if (entry.getKey().equals("method")) continue;
//            paramsMap.put(entry.getKey(), entry.getValue()[0]);
//        }

        //高级转换 -> Map<String, String[]> -> Map<String, String> ???
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, String> paramsMap = parameterMap.entrySet()
                .stream()
                .filter(entry -> !entry.getKey().equals("method"))
                //stream -> Entry,Entry,Entry...
                .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue()[0]));


//        Map<String, String> paramsMap = ... //将异步通知中收到的所有参数都存放到map中
        boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap,
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx+n+pEqTVi27mtj3CuUQXi2ixqeeTwE/0tGrW+sg6xtfajvJV67GYf2zzNxxBV0TYfhdbi70VI3DftEijg7GSNKoOilAu2DKQFqidnSxmN1Es1oRTaiaehqm1Uzs2uswpzBVR21iygLHujwthC8kNkMgxVFkjbE/qTn7z5wlsailtg6wF+hY3BcDCiaLyVLjEDngmrLyLXPLenjAuvXq20h9zV7CW9HXuhpPBDfsn4fv5TjgEl1smjJNr4O/VxICKDNPsvrCyNXhfroK9PEFFwH+4IWGeBUJAP2cSufNU0OA+UH+2xQnaR8Cz30QIgIslckBGuXQZvxqaY2mMMz14QIDAQAB",
                "utf-8",
                "RSA2"); //调用SDK验证签名
        if(signVerified){
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            //获取订单号
            String orderId = paramsMap.get("out_trade_no");
            //获取支付金额
            String money = paramsMap.get("total_amount");
            //根据订单号查询订单详情
            Orders orders = ordersService.getOrdersByOid(orderId);
            //比较订单总金额
            double moneys = Double.parseDouble(money);
            if (orders.getMoney() != moneys) {
                //校验未通过
                return "failure";
            }

            //校验通过
            orders.setUpdateTime(new Date());
            orders.setStatus(1);//已支付
            int result = ordersService.updateOrders(orders);
//            if (result > 0) {
                //-----------TODO 一定获取不到session的-------------
//                //订单修改成功 同步的修改session
//                Player player = (Player) session.getAttribute("login_user");
//                player.setHappyBean(player.getHappyBean() + orders.getHappeyBean());
//                session.setAttribute("login_user", player);
//            }
            return "success";
        }else{
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            System.out.println("支付验证未通过");
            return "failure";
        }
    }
}
